const imghash = require('imghash');
const hamming = require('hamming-distance');
var fs = require('fs');
var cluster = require("cluster");
//const hash2 = imghash.hash('../images/QD2/QD2图(10)2362x2362.jpg');
var results = [];
const baseUrl = "../images/";
function calculate(hash1, results, sig, imgArr, cname) {
	console.log("sig ====" + sig + "===============" + imgArr.length);
	if (sig >= imgArr.length) {
		console.log(results);
		return;
	}
	var imgUrl = "../images/" + cname + "/" + imgArr[sig];
	var hash2 = imghash.hash(imgUrl);
	Promise
		.all([hash1, hash2])
		.then((r) => {
			const dist = hamming(r[0], r[1]);
			console.log(`Distance between images is: ${dist}`);
			if(dist <= 20) {
				console.log('Images are similar' + "=====" + sig);
				results.push(imgArr[sig]);
			} else {
				console.log('Images are NOT similar');
			}
			calculate(hash1, results, sig + 1, imgArr);
		});
}

var cs = fs.readdirSync(baseUrl);
function search(cnames, iterate, results, hash1) {
	if (iterate >= cnames.length) {
		console.log(results);
		return;
	}
	console.log();
	var imgArr = fs.readdirSync(baseUrl + cnames[iterate]);
	calculate(hash1, results, 0, imgArr, cname);
}

function readCollection(cs, tempImg) {
	var result = [];
	var hashTemp = imghash.hash('../images/QD2/QD2图(1)4085x4071.jpg');
	for (var i = 0; i < cs.length; i++) {
		var nextUrl = baseUrl + cs[i];
		var imgArr = fs.readdirSync(nextUrl);
		console.log(imgArr);
		for (var j = 0; j < imgArr.length; j++) {
			var imgUrl = nextUrl + "/" + imgArr[i],
				hashSearch = imghash.hash(imgUrl);
		}
	}
}

module.exports = calculate;

